package com.example.kcb;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import java.util.Locale;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    //当前头像
    private de.hdodenhof.circleimageview.CircleImageView icon;
    // 头像Bitmap
    private Bitmap head;
   // private static String path=Environment.getExternalStorageDirectory().getAbsolutePath()+"/kcb";
   // sd路径
    private static String path = "sdcard/myHead/";
    //滑动菜单
    private DrawerLayout mDrawerLayout;
    //星期几
    private RelativeLayout day;
    //当前日期
    protected TextView dateTextView;
    //toast事件
    public static Toast mToast;
    //SQLite Helper类
    private DatabaseHelper databaseHelper = new DatabaseHelper
            (this);

    private int hegiht = 130;

    final int[] course_bj = {R.drawable.coursetable1, R.drawable.coursetable2,
            R.drawable.coursetable3, R.drawable.coursetable4, R.drawable.coursetable5,
            R.drawable.coursetable6, R.drawable.coursetable7, R.drawable.coursetable8,
            R.drawable.coursetable9, R.drawable.coursetable10};

    @RequiresApi(api = Build.VERSION_CODES.N)


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 添加横线背景
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
        int lineSpacingPx = 50;
        HorizontalLinesView bgLines = new HorizontalLinesView(this, lineSpacingPx, 1);
        frameLayout.addView(bgLines, 0);

        //左边侧滑菜单
        mDrawerLayout = (DrawerLayout)findViewById(R.id.draw);
        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
        //工具条
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        navView.setCheckedItem(R.id.score);
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
            @Override
            public boolean onNavigationItemSelected(MenuItem item){
                switch (item.getItemId()){
                    case R.id.add_courses:
                        Intent intent = new Intent(MainActivity.this, AddCourseActivity.class);
                        startActivityForResult(intent, 0);
                        break;
                    case R.id.course_records:
                        Intent intent1 = new Intent(MainActivity.this, CourseRecordsActivity.class);
                        startActivity(intent1);
                        break;
                    case R.id.menu_about:
                        Intent intent2 = new Intent(MainActivity.this, AboutActivity.class);
                        startActivity(intent2);
                        break;
                    default:
                        System.out.println("错误");
                }
                mDrawerLayout.closeDrawers();
                return true;
            }
        });
        //创建课程表左边视图(节数)
        createLeftView();
        //从数据库读取数据
        loadData();
        //获取系统时间
        dateTextView = (TextView) navView.getHeaderView(0).findViewById(R.id.Menu_main_textDate);
        //获取头像
        icon = (de.hdodenhof.circleimageview.CircleImageView) navView.getHeaderView(0).findViewById(R.id.icon_image);
        //初始化日期与头像
        initDate();
        initView();
        //相机拍摄不成功时，加上这三行代码
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

    }

    //从数据库加载数据
    private void loadData() {
        ArrayList<Course> coursesList = new ArrayList<>(); //课程列表
        SQLiteDatabase db = databaseHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM courses", null);
        // 清空所有星期布局
        clearCourseViews();
        if (cursor.moveToFirst()) { // 确保游标移动到第一行
            do {
                String courseName = cursor.getString(cursor.getColumnIndex("course_name"));
                String teacher = cursor.getString(cursor.getColumnIndex("teacher"));
                String classRoom = cursor.getString(cursor.getColumnIndex("class_room"));
                int day = cursor.getInt(cursor.getColumnIndex("day"));
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                String period = cursor.getString(cursor.getColumnIndex("period"));
                Course course = new Course(courseName,teacher,classRoom,day,period);
                course.setId(id);
                coursesList.add(course);
            } while (cursor.moveToNext());
        }
        cursor.close();

        //使用从数据库读取出来的课程信息来加载课程表视图
        for (Course course : coursesList) {
            createCourseView(course);
        }
    }
    private void clearCourseViews() {
        // 清空所有星期布局中的视图
        RelativeLayout mondayLayout = (RelativeLayout) findViewById(R.id.monday);
        RelativeLayout tuesdayLayout = (RelativeLayout) findViewById(R.id.tuesday);
        RelativeLayout wednesdayLayout = (RelativeLayout) findViewById(R.id.wednesday);
        RelativeLayout thursdayLayout = (RelativeLayout) findViewById(R.id.thursday);
        RelativeLayout fridayLayout = (RelativeLayout) findViewById(R.id.friday);
        RelativeLayout saturdayLayout = (RelativeLayout) findViewById(R.id.saturday);
        RelativeLayout weekdayLayout = (RelativeLayout) findViewById(R.id.weekday);

        mondayLayout.removeAllViews();
        tuesdayLayout.removeAllViews();
        wednesdayLayout.removeAllViews();
        thursdayLayout.removeAllViews();
        fridayLayout.removeAllViews();
        saturdayLayout.removeAllViews();
        weekdayLayout.removeAllViews();
    }
    //保存数据到数据库
    private long saveData(Course course) {
        SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
        // 使用 insert() 方法插入数据并获取新插入行的行 ID
        long newId = sqLiteDatabase.insert("courses", null, courseToContentValues(course));
        sqLiteDatabase.close(); // 关闭数据库连接
        return newId; // 返回新插入行的行 ID
    }

    private ContentValues courseToContentValues(Course course) {
        ContentValues values = new ContentValues();
        values.put("course_name", course.getCourseName());
        values.put("teacher", course.getTeacher());
        values.put("class_room", course.getClassRoom());
        values.put("day", String.valueOf(course.getDay()));
        values.put("period", course.getPeriod());
        return values;
    }

    //创建课程节数视图
    private void createLeftView() {
        String[] periods = {
                "早读", "1", "2", "3", "4",
                "午自习", "5", "6", "7", "8",
                "夕会课", "晚自习-1", "晚自习-2", "晚自习-3"
        };
        LinearLayout leftViewLayout = (LinearLayout) findViewById(R.id.left_view_layout);

        for (int i = 0; i < periods.length; i++) {
            // 1. inflate 原始卡片
            View view = LayoutInflater.from(this).inflate(R.layout.left_view, null);
            LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(150, hegiht);
            view.setLayoutParams(cardParams);

            // 2. 填文字
            TextView text = (TextView) view.findViewById(R.id.class_number_text);
            text.setText(periods[i]);
//            if(0 == i){
//                text.setBackgroundResource(course_bj[0]);
//            }else if(5 == i){
//                text.setBackgroundResource(course_bj[3]);
//            }else if(10 == i){
//                text.setBackgroundResource(course_bj[8]);
//            }else {
//                text.setBackgroundResource(course_bj[2]);
//            }
            // 3. 再包一层竖直 LinearLayout，把卡片+横线放进去
            LinearLayout itemWrap = new LinearLayout(this);
            itemWrap.setOrientation(LinearLayout.VERTICAL);
            itemWrap.addView(view);

            View line = new View(this);
            LinearLayout.LayoutParams lineParams =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
            line.setBackgroundColor(Color.parseColor("#FFCCCCCC"));
            itemWrap.addView(line, lineParams);

            // 4. 把这一整包扔进左侧容器
            leftViewLayout.addView(itemWrap);
        }
    }

    /**
     * 真正把当前课程插入 course_records 表
     */
    private void realInsert(Course course) {
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        db.insert("course_records", null, courseInfoToContentValues(course));
        db.close();                 // 只关一次就够了
        Toast.makeText(MainActivity.this, "课程记录已添加", Toast.LENGTH_SHORT).show();
    }
    //创建课程视图
    private void createCourseView(final Course course) {

            int getDay = course.getDay();
            String period = course.getPeriod(); // 课程节次
            if ((getDay < 1 || getDay > 7)) {
                if (mToast == null) {
                    mToast = Toast.makeText(this, "星期几输错,或课程节次输错，请重新输入", Toast.LENGTH_SHORT);
                } else {
                    mToast.setText("星期几输错,或课程节次输错，请重新输入");
                    mToast.setDuration(Toast.LENGTH_SHORT);
                }
                mToast.show();
            } else {
                switch (getDay) {
                    case 1:
                        day = (RelativeLayout) findViewById(R.id.monday);
                        break;
                    case 2:
                        day = (RelativeLayout) findViewById(R.id.tuesday);
                        break;
                    case 3:
                        day = (RelativeLayout) findViewById(R.id.wednesday);
                        break;
                    case 4:
                        day = (RelativeLayout) findViewById(R.id.thursday);
                        break;
                    case 5:
                        day = (RelativeLayout) findViewById(R.id.friday);
                        break;
                    case 6:
                        day = (RelativeLayout) findViewById(R.id.saturday);
                        break;
                    case 7:
                        day = (RelativeLayout) findViewById(R.id.weekday);
                        break;
                }
                if (day != null) {
                    System.out.printf("11" + period);
                    int periodIndex = getPeriodIndex(period);
                    final View v = LayoutInflater.from(this).inflate(R.layout.course_card, null); //加载单个课程布局
//                    v.setY(hegiht * (periodIndex)); // 设置开始高度，即第几节课开始
//                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                            ViewGroup.LayoutParams.MATCH_PARENT, hegiht); // 设置布局高度为单节课
//                    v.setLayoutParams(params);

                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, hegiht);
                    params.topMargin = hegiht * periodIndex;
                    v.setLayoutParams(params);
                    TextView text = (TextView) v.findViewById(R.id.text_view);

//                    text.setBackgroundResource(course_bj[(int) (Math.random() * 10)]);
                    if(0 == periodIndex){
                        text.setBackgroundResource(course_bj[0]);
                    }else if(5 == periodIndex){
                        text.setBackgroundResource(course_bj[3]);
                    }else if(10 == periodIndex){
                        text.setBackgroundResource(course_bj[8]);
                    }else {
                        text.setBackgroundResource(course_bj[2]);
                    }
                    text.setText(course.getCourseName() + course.getClassRoom()); //显示课程名
                    day.addView(v);
                    //长按删除课程
                    v.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            // 弹出对话框确认是否标记课程为已上课
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("确认上课")
                                    .setMessage("您确定这节课已经上过了吗？")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            /* ========== 1. 星期校验 ========== */
                                            Calendar todayCal = Calendar.getInstance();
                                            int todayWeek = todayCal.get(Calendar.DAY_OF_WEEK);   // 1=周日 ... 7=周六
                                            int todayCourseDay = (todayWeek == Calendar.SUNDAY) ? 7 : todayWeek - 1; // 转成 1=周一 ... 7=周日

                                            if (todayCourseDay != course.getDay()) {   // course.getDay() 就是 1~7
                                                Toast.makeText(MainActivity.this,
                                                        "今天不是上课日（课程定在周" + course.getDay() + "）", Toast.LENGTH_SHORT).show();
                                                return;          // 直接退出
                                            }

                                            /* ========== 2. 今日是否已添加校验 ========== */
                                            String todayStr = new java.text.SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                                                    .format(todayCal.getTime());

                                            SQLiteDatabase db = databaseHelper.getReadableDatabase();
                                            Cursor cursor = db.query(
                                                    "course_records",                       // 表
                                                    new String[]{"id"},                     // 只查一列即可
                                                    "course_id = ? AND record_time = ?",    // 条件
                                                    new String[]{String.valueOf(course.getId()), todayStr},
                                                    null, null, null);

                                            boolean exists = cursor.moveToFirst();
                                            cursor.close();

                                            if (exists) {
                                                // 2.1 已存在 → 二次确认
                                                new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
                                                        .setTitle("重复添加")
                                                        .setMessage("课程今天已添加过一次，您要再次添加吗？")
                                                        .setPositiveButton("仍要添加", (d, w) -> realInsert(course))   // 真正插入
                                                        .setNegativeButton("取消", null)
                                                        .show();
                                            } else {
                                                realInsert(course);
                                            }



                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            // 用户取消，不执行任何操作
                                        }
                                    })
                                    .show();
                            return true;
                        }
                    });
                    v.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(MainActivity.this, MessageCourseActivity.class);
                            intent.putExtra("course", course);
                            startActivity(intent);
                        }
                    });
                }
            }
    }

    private ContentValues courseInfoToContentValues(Course course) {
        ContentValues values = new ContentValues();
        values.put("course_name", course.getCourseName());
        values.put("class_room", course.getClassRoom());
        values.put("teacher", course.getTeacher());
        String recordTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); // 系统当前时间
        values.put("record_time", recordTime);
        values.put("period", course.getPeriod());
        values.put("date", String.valueOf(course.getDay()));
        values.put("state", "1");
        values.put("course_id", String.valueOf(course.getId()));
        return values;
    }

    // 辅助方法，根据节次名称获取索引（假设早自习为0，1-10为正常课程节次）
    private int getPeriodIndex(String period) {
        switch (period) {
            case "早读":
                return 0;
            case "1":
                return 1;
            case "2":
                return 2;
            case "3":
                return 3;
            case "4":
                return 4;
            case "午自习":
                return 5;
            case "5":
                return 6;
            case "6":
                return 7;
            case "7":
                return 8;
            case "8":
                return 9;
            case "夕会课":
                return 10;
            case "晚自习-1":
                return 11;
            case "晚自习-2":
                return 12;
            case "晚自习-3":
                return 13;
            default:
                return Integer.parseInt(period);
        }
    }
    public void createLoginView(){
        final View v = LayoutInflater.from(this).inflate(R.layout.login, null); //加载登陆布局
        v.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //从相册里面取相片的返回结果
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                }

                break;
            //调用系统裁剪图片后
            case 2:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");

                    if (head != null) {
                        setPicToView(head);// 保存在SD卡中
                        icon.setImageBitmap(head);// 用CicleImageView显示出来
                    }
                }
                break;
            //调用拍摄功能
            case 3:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/profile.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                }

                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 0 && data != null) {
            Course course = (Course) data.getSerializableExtra("course");
            SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
            // 查询数据库中是否已存在相同 day 和 period 的课程
            String selection = "day=? AND period=?";
            String[] selectionArgs = new String[]{String.valueOf(course.getDay()), course.getPeriod()};
            Cursor cursor = sqLiteDatabase.query("courses", null, selection, selectionArgs, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                // 如果存在相同 day 和 period 的课程，提示用户
                Toast.makeText(this, "课程已存在", Toast.LENGTH_SHORT).show();
                cursor.close();
                return;
            }
            if (cursor != null) {
                cursor.close();
            }
            //存储数据到数据库
            long id = saveData(course);
            course.setId((int) id);
            //创建课程表视图
            createCourseView(course);
        }
    }
    public void test_click(View v){
        Intent intent5 = new Intent(MainActivity.this, AddCourseActivity.class);
        startActivityForResult(intent5, 0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }
        @SuppressLint("SimpleDateFormat")
        private void initDate() {
            Date currentTime = new Date();
            String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
            Calendar cal = Calendar.getInstance();
            cal.setTime(currentTime);
            int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (w < 0)  w = 0;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日  ");
            String dateString = formatter.format(currentTime);
            dateTextView.setText(dateString + "星期" + weekDays[w]);
        }
     public void change_image(View v){
         initView();
         showTypeDialog();
      }
    /**
     * 生成一条贯穿 7 天的灰色横线
     */
    private View createBottomDivider() {
        View line = new View(this);
        int dp1 = (int) (getResources().getDisplayMetrics().density * 1 + 0.5f);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, dp1);
        line.setLayoutParams(lp);
        line.setBackgroundColor(Color.parseColor("#FFCCCCCC"));
        line.setId(View.generateViewId());   // API 17+，防止重复
        return line;
    }
    private void initView() {
        Bitmap bt = Login.getLocalBitmap(path+"profile.jpg");
        if (bt != null) {
            icon.setImageBitmap(bt);
        } else {
            /**
             * 如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */
        }
    }

    private void showTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        final View change = LayoutInflater.from(this).inflate(R.layout.change_user_image, null);
        TextView select_gallery = (TextView) change.findViewById(R.id.select_gallery);
        TextView select_camera = (TextView) change.findViewById(R.id.select_camera);
        select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
            @Override
            public void onClick(View v) {
                Intent changepho = new Intent(Intent.ACTION_PICK, null);
                changepho.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(changepho,1);
                dialog.dismiss();
            }
        });
        select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机
            @Override
            public void onClick(View v) {
                Intent changecam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                changecam.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "profile.jpg")));
                startActivityForResult(changecam, 3);
                dialog.dismiss();
            }
        });
        dialog.setView(change);
        dialog.show();
        initView();
    }

    /**
     * 调用系统的裁剪功能
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "profile.jpg";// 图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences prefs = getSharedPreferences("refresh_flag", MODE_PRIVATE);
        boolean needsRefresh = prefs.getBoolean("refresh", false);
        if (needsRefresh) {
            prefs.edit().putBoolean("refresh", false).apply();
            loadData(); // 重新加载数据
        }
    }
}


